/*
 * Copyright (c) 2017, www.zm0618.com All Rights Reserved..
 */

package com.light.hessian.exporter.registry.config;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by zhaojun on 2017/02/17.
 */
public class ConsulRegistryConfigParser implements ServiceRegistryConfigParser {

    protected static final Logger logger= LoggerFactory.getLogger(ConsulRegistryConfigParser.class);

    private static int getSecondNum(String  secondConf){
        Pattern  secondPatten=Pattern.compile("^(\\d)+s$");
        Matcher matcher = secondPatten.matcher(secondConf);
        if (matcher.find()){
            String g = matcher.group();
            String secondNum = g.substring(0, g.length() - 1);
            return Integer.parseInt(secondNum);
        }
        return 0;
    }

    @Override
    public ServiceRegistryConfig doParse(ServiceRegistry autoRegister, Environment env) {

        String nameSpace=autoRegister.getNameSpace();

        Properties configProperties = autoRegister.getConfigProperties();

        String address=StringUtils.trim(configProperties.getProperty(String.format("%s.service.bind.address",nameSpace),env.getProperty("server.address","localhost")));//服务绑定地址
        String protocol=StringUtils.trim(configProperties.getProperty(String.format("%s.service.bind.protocol",nameSpace),"http"));
        String port=StringUtils.trim(configProperties.getProperty(String.format("%s.service.bind.port",nameSpace),env.getProperty("server.port","8080")));

        String portOffset=StringUtils.trim(configProperties.getProperty(String.format("%s.service.bind.offset",nameSpace),"0"));
        int portInt = Integer.parseInt(port) + Integer.parseInt(portOffset);

        String defaultPrefixPath=env.getProperty("server.servlet-path","/");

        String prefixPath=StringUtils.trim(configProperties.getProperty(String.format("%s.service.bind.path.prefix",nameSpace),defaultPrefixPath));


        //监控检测注册信息
        String healthcheckConfig=configProperties.getProperty(String.format("%s.service.health.endpoint.healthcheck",nameSpace));

        //从springboot环境变量中获取相关配置信息
        if (StringUtils.isNotBlank(healthcheckConfig)){

            healthcheckConfig=StringUtils.replace(healthcheckConfig,"${server.address}",address);

            healthcheckConfig=StringUtils.replace(healthcheckConfig,"${server.servlet-path}",prefixPath);

            healthcheckConfig=StringUtils.replace(healthcheckConfig,"${server.port}",String.valueOf(portInt));

            String managementAddress=env.getProperty("management.address");
            if (StringUtils.isNotBlank(managementAddress)){
                healthcheckConfig=StringUtils.replace(healthcheckConfig,"${management.address}",managementAddress);
            }
            String managementPort=env.getProperty("management.port");
            if (StringUtils.isNotBlank(managementPort)){
                healthcheckConfig=StringUtils.replace(healthcheckConfig,"${management.port}",managementPort);
            }
            String managementContextPath=env.getProperty("management.context-path");
            if (StringUtils.isNotBlank(managementContextPath)){
                healthcheckConfig=StringUtils.replace(healthcheckConfig,"${management.context-path}",managementContextPath);
            }
        }

        String healthcheck=healthcheckConfig;
        String healthcheckInterval=StringUtils.trim(configProperties.getProperty(String.format("%s.service.health.healthcheck.interval",nameSpace),"5s"));
        String healthcheckTimeout=StringUtils.trim(configProperties.getProperty(String.format("%s.service.health.healthcheck.timeout",nameSpace),"20s"));



        String isReport=StringUtils.trim(configProperties.getProperty(String.format("%s.service.health.report.status",nameSpace),"false"));
        String reportinterval=StringUtils.trim(configProperties.getProperty(String.format("%s.service.health.report.interval",nameSpace),"10s"));



        //注册中心节点
        String nodes=StringUtils.trim(configProperties.getProperty(String.format("%s.service.registry.nodes",nameSpace),"localhost:8500"));
        String transportProtocol=StringUtils.trim(configProperties.getProperty(String.format("%s.service.registry.transport.protocol",nameSpace),"http"));
        String token=StringUtils.trim(configProperties.getProperty(String.format("%s.service.registry.token",nameSpace),null));

        String[] node= StringUtils.split(nodes,",");

        if (ArrayUtils.isEmpty(node)){
            throw new RuntimeException("there is no nodes config!");
        }

        List<String> nodeList=new ArrayList<String>();
        for (int i = 0; i <node.length ; i++) {
            nodeList.add(StringUtils.trim(node[i]));
        }

        boolean isRportBoolean=Boolean.parseBoolean(isReport);
        int reportfrequencyInt=getSecondNum(reportinterval);

        ConsulRegistryExportConfig config=new ConsulRegistryExportConfig();
        config.setHealthCheck(healthcheck);
        config.setHealthCheckInterval(healthcheckInterval);
        config.setHealthCheckTimeout(healthcheckTimeout);

        config.setReportInterval(reportfrequencyInt);
        config.setReportStatus(isRportBoolean);

        config.setToken(token);
        config.setTransProtocol(transportProtocol);
        config.setRegistryNodes(nodeList);
        config.setRegistryType(RegistryType.consul);

        config.setAddress(address);
        config.setProtocol(protocol);
        config.setPrefixPath(prefixPath);
        config.setPort(portInt);

        return config;
    }
}
